package com.xckj.cycling.service

import android.app.*
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.xckj.cycling.R
import com.xckj.cycling.activity.MainActivity
import com.xckj.cycling.activity.SplashActivity
import com.xckj.cycling.context.AppContext

/**
 * 骑行的前台service
 */
class CyclingService : Service() {
    companion object {
        fun start() {
            AppContext.globalContext().startForegroundService(
                Intent(
                    AppContext.globalContext(),
                    CyclingService::class.java
                )
            )
        }

        fun stop() {
            AppContext.globalContext().stopService(
                Intent(
                    AppContext.globalContext(),
                    CyclingService::class.java
                )
            )
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        startForeground(100, createNotificaition())
    }

    fun createNotificaition(): Notification {
        val channelId = "cycling"
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        manager.createNotificationChannel(
            NotificationChannel(
                channelId,
                "Cycling",
                NotificationManager.IMPORTANCE_DEFAULT
            )
        )
        return NotificationCompat.Builder(this, channelId)
            .setContentTitle(getString(R.string.app_name))
            .setContentText("Cycling...").setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(
                PendingIntent.getActivity(
                    this,
                    1000,
                    Intent(
                        this,
                        SplashActivity::class.java
                    ).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                )
            )
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)).build()

    }
}